<?php

namespace app\admin\controller;

use app\admin\AdminCommon;
use app\admin\model\GoodsColor;
use think\console\Input;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class Goods extends AdminCommon
{
    public function getIndex()
    {
        //商品的展现
        $goods=$goods=Db::name('goods')
            ->alias('g')
            ->join('category gc','g.goods_class=gc.id','left')
            ->join('brand gb','g.goods_brand=gb.id')
            ->field('g.id,g.goods_class,g.goods_brand,gc.catname,gb.brand_name,g.goods_name,g.goods_pic,g.goods_overview,g.goods_price,g.goods_unit,g.goods_status')
            ->select();
        $this->assign('data',$goods);
        return $this -> fetch('goods/index');
    }
    //商品的创建页面
    public function getAdd()
    {
        $Category=new \app\admin\model\Category();
        $data=$Category->tree();
        $this->assign('data',$data);
        return $this -> fetch('goods/create');
    }
    //商品的保存
    public function postDoadd(Request $request)
    {
        $input = $request->except('file,action,__token__,goods_model');

        //商品分类的选择
        if (@$input['goods_class_sec']) {
            unset($input['goods_class_top']);
            $input['goods_class'] = $input['goods_class_sec'];
            unset($input['goods_class_sec']);
        } else {
            $input['goods_class'] = $input['goods_class_top'];
            unset($input['goods_class_top']);
        }
        //用表关联的方法进行数据存储
        $goods = new \app\admin\model\Goods();
        $goods->data($input);
        if ($goods->save()) {
            $id = Db::name('goods')->getLastInsID();
            Db::startTrans();
            try {
                // 写入关联数据
                //提出中间的类型数据存入类型表中
                $models = input('post.goods_model/a');
                foreach ($models as $val) {
                    $model['gid'] = $id;
                    $model['mid'] = $val;
                    Db::name('goods_model')->insert($model);
                }
                    // 提交事务
                Db::commit();
                $data = [
                    'status' => 0,
                    'msg' => '商品添加成功',
                ];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $goods->where('id',$id)->delete();
                $data = [
                    'status' => 1,
                    'msg' => '商品添加失败',
                ];
            }
            return json($data);
        }else{
            $data = [
                'status' => 2,
                'msg' => '商品添加失败',
            ];

        }
        return json($data);
    }
    //图片上传的处理
    public function postPics(){
        $file=\request()->file('file');
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/goods_pic');
            if($info){
                $path =  $info->getSaveName();
                return json(array('status'=>1,'path'=>$path,'msg'=>'图片上传成功'));
            }else{
                // 上传失败获取错误信息
//                echo $file->getError();
                return json(array('status'=>0,'msg'=>'上传失败'));
            }
        }
    }
    //商品的编辑
    public function getEdit($id){
        //目录的得到
        $Category=new \app\admin\model\Category();
        $data=$Category->tree();
        $this->assign('data',$data);
        //商品的得到
        $goodsArr=new  \app\admin\model\Goods;
        $goods=$goodsArr->where('id',$id)->select();

        $this->assign('goods',$goods);
        //栏目的得到
        foreach ($goods as $val) {
            $goods_class = $val['goods_class'];
            $goods_brand = $val['goods_brand'];
        }
        $catname=Db::name('category')->where('id',$goods_class)->value('catname');
        $goods_brand=Db::name('brand')->where('id',$goods_brand)->value('brand_name');
        $this->assign('catname',$catname);
        $this->assign('brand_name',$goods_brand);
        //商品与型号的关系信息表
        $models=Db::name('goods_model')->where('gid',$id)->select();
        $mids[]='';
        foreach ($models as $val){
            $mids[]=$val['mid'];
        }
        $this->assign('mids',$mids);
        //型号的信息表
        $model=Db::name('models')->select();
        $this->assign('model',$model);
        //载入页面
        return $this->fetch('goods/edit');
    }
    //编辑写入
    public function postDoedit(Request $request)
    {
        $input = ($request->except('goods_color,file,action,goods_model'));
        //首先判断是否有新分类传来
        if(@$input['goods_class_top'] || @$input['goods_class_sec']){
            if(@$input['goods_class_sec']){
                unset($input['goods_class_top']);
                $input['goods_class']=$input['goods_class_sec'];
                unset($input['goods_class_sec']);
            }else{
                $input['goods_class']=$input['goods_class_top'];
                unset($input['goods_class_top']);
            }
        }else{
            unset($input['goods_class_top']);
            unset($input['goods_class_sec']);
        }
        if(@$input['goods_brand_new']){
            $input['goods_brand']=$input['goods_brand_new'];
            unset($input['goods_brand_new']);
        }else{
            unset($input['goods_brand_new']);
        }
        $id = $input['id'];
        //需要判断是否有新的图片上传，如果有就必须要删除已经存储的图片
        $old_pic = $input['old_goods_pic'];
        $pic = $input['goods_pic'];
        if ($old_pic != $pic) {
            //不等于就说明上传了新的图片，就删除原有的图片
            $path = './uploads/goods_pic/' . $old_pic;
            if (file_exists($path) && is_file($path)) {
                //存在就删除图片
                if (unlink($path)) {
                    //图片删除成功才进行数据库更新
                    unset($input['old_goods_pic']);
                    $goods = \app\admin\model\Goods::get($id);
                    $goods->data($input);
                    if ($goods->save()) {
                        Db::startTrans();
                        try {
                            // 写入关联数据
                            //先删除原本的
                            Db::name('goods_model')->where('gid', $id)->delete();
                            //提出中间的类型数据存入类型表中
                            $models = input('post.goods_model/a');
                            foreach ($models as $val) {
                                $model['gid'] = $id;
                                $model['mid'] = $val;
                                Db::name('goods_model')->insert($model);
                            }
                            // 提交事务
                            Db::commit();
                            $data = [
                                'status' => 0,
                                'msg' => '商品添加成功',
                            ];
                        } catch (\Exception $e) {
                            // 回滚事务
                            Db::rollback();
                            $data = [
                                'status' => 1,
                                'msg' => '商品添加失败',
                            ];
                        }
                        return json($data);
                    }else{
                        $data = [
                            'status' => 2,
                            'msg' => '商品添加失败',
                        ];
                    }
                    return json($data);
                    }

            } else {
                //就算是老图片不存在，也要进行修改
                unset($input['old_goods_pic']);
                $goods = \app\admin\model\Goods::get($id);
                $goods->data($input);
                if ($goods->save()) {
                    Db::startTrans();
                    try {
                        // 写入关联数据
                        //先删除原本的
                        Db::name('goods_model')->where('gid', $id)->delete();
                        //提出中间的类型数据存入类型表中
                        $models = input('post.goods_model/a');
                        foreach ($models as $val) {
                            $model['gid'] = $id;
                            $model['mid'] = $val;
                            Db::name('goods_model')->insert($model);
                        }
                        // 提交事务
                        Db::commit();
                        $data = [
                            'status' => 0,
                            'msg' => '已重新上传图片并更新',
                        ];
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        $data = [
                            'status' => 1,
                            'msg' => '商品更新失败',
                        ];
                    }
                    return json($data);

                } else {
                    $data = [
                        'status' => 1,
                        'msg' => '商品修改失败',
                    ];
                }
                return json($data);
            }
        }else{
                //不上传新图片的更新
                unset($input['old_goods_pic']);
                $goods = \app\admin\model\Goods::get($id);
                $goods->data($input);
                if ($goods->save()) {
                    Db::startTrans();
                    try {
                        // 写入关联数据
                        //先删除原本的
                        Db::name('goods_model')->where('gid', $id)->delete();
                        //提出中间的类型数据存入类型表中
                        $models = input('post.goods_model/a');
                        foreach ($models as $val) {
                            $model['gid'] = $id;
                            $model['mid'] = $val;
                            Db::name('goods_model')->insert($model);
                        }
                        // 提交事务
                        Db::commit();
                        $data = [
                            'status' => 0,
                            'msg' => '商品更新成功',
                        ];
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        $data = [
                            'status' => 1,
                            'msg' => '商品更新失败',
                        ];
                    }
                    return json($data);

                }else {
                    $data = [
                        'status' => 1,
                        'msg' => '商品更新失败'
                    ];

                }
            return json($data);
            }
        }
    //单个商品的删除
    public function postDelete($id){
        $goods=\app\admin\model\Goods::get($id);
        //查到商品图片的链接
        $path=$goods->where('id',$id)->value('goods_pic');
        $path='./uploads/goods_pic/'.$path;
        if ($goods->delete()){
            //表删除成功就删除图片
            if (file_exists($path) && is_file($path)) {
                //存在就删除图片
                if (unlink($path)) {
                    $paths=pathinfo($path,PATHINFO_DIRNAME);
                    if(count(scandir($paths))==2)
                    {
                        rmdir($paths);
                    }
                    // 删除关联的商品颜色
                    Db::name('goods_model')->where('gid',$id)->delete();
                    $data = [
                        'status' => 0,
                        'msg' => '商品删除成功'
                    ];
                } else {
                    // 删除关联的商品颜色
                    Db::name('goods_model')->where('gid',$id)->delete();
                    $data = [
                        'status' => 1,
                        'msg' => '文件删除失败'
                    ];
                }
            }else {
                // 删除关联的商品颜色
                Db::name('goods_model')->where('gid',$id)->delete();
                $data = [
                    'status' => 2,
                    'msg' => '文件不存在'
                ];
            }
        } else {
            $data = [
                'status' => 3,
                'msg' => '出现未知错误'
            ];
        }
            return json($data);
    }
    //多商品的批量删除
    public function postDatadel($ids){
        //商品的删除
        $ids=explode(',',$ids);
        //获取每条数据的图片path
        $paths=array();
        Db::startTrans();
        $status = '';
        foreach ($ids as $id){
            $goods=\app\admin\model\Goods::get($id);
            //查到商品图片的链接
            $path=$goods->where('id',$id)->value('goods_pic');
            $path='./uploads/goods_pic/'.$path;
            array_push($paths,$path);
            if($status === false){
                Db::rollback();
                $data = [
                    'status' => 1,
                    'msg' => '数据删除失败',
                ];
                return json($data);
            }
            if ($goods->delete()){
                //表删除成功就删除颜色表
                // 删除关联的商品颜色
                Db::name('goods_model')->where('gid',$id)->delete();
                //表删除成功的时候，把文件路径储存到数组
                $status = true;
            } else {
                $status = false;
            }
        }
        // 提交事务
        Db::commit();
        //进行文件的删除
        if($status !== true){
            $data = [
                'status' => 2,
                'msg' => '出现未知错误，请稍后重试',
            ];
            return json($data);
        }
        foreach ($paths as $path){
            if($status === false){
                $data = [
                    'status' => 0,
                    'msg' => '数据删除成功,但图片删除失败',
                ];
                return json($data);
            }
            if (file_exists($path) && is_file($path)){
                //存在就删除图片
                if (unlink($path)){
                    $paths=pathinfo($path,PATHINFO_DIRNAME);
                    if(count(scandir($paths))==2)
                    {
                        rmdir($paths);
                    }
                    $status = true;
                } else {
                    $status = false;
                }
            } else {
                $status = false;
            }
        }
        $data = [
            'status' => 0,
            'msg' => '数据删除成功',
        ];
        return json($data);
    }
    //商品的停用
    public function postStop($id)
    {
        //
        $admin=new \app\admin\model\Goods();
        $result=$admin->save([
            'goods_status'  => '1',
        ],['id' => $id]);
        if($result){
            $data=
                [
                    'status'=>0,
                    'msg'=>'已停用',
                    'id'=>$id,
                ];
        }else{
            $data=
                [
                    'status'=>1,
                    'msg'=>'出现未知错误，请稍后重试',
                    'id'=>$id,
                ];
        }
        return json($data);
    }
    //商品的启用
    public function postStart($id)
    {
        //
        $admin=new \app\admin\model\Goods();
        $result=$admin->save([
            'goods_status'  => '0',
        ],['id' => $id]);
        if($result){
            $data=
                [
                    'status'=>0,
                    'msg'=>'已启用',
                    'id'=>$id,
                ];
        }else{
            $data=
                [
                    'status'=>1,
                    'msg'=>'出现未知错误，请稍后重试',
                    'id'=>$id,
                ];
        }
        return json($data);
    }
    //商品详情
    public function getDetail($id){
        //商品的详情
        $goods=$goods=Db::name('goods')
            ->alias('g')
            ->join('category gc','g.goods_class=gc.id','left')
            ->join('brand gb','g.goods_brand=gb.id')
            ->field('g.id,g.goods_class,g.goods_brand,gc.catname,gb.brand_name,g.goods_name,g.goods_pic,g.goods_overview,g.goods_price,g.goods_unit,g.goods_status,g.goods_order,g.goods_num,g.goods_introduce')
            ->where('g.id',$id)
            ->find();
//        print_r($goods);
//        exit;
        $this->assign('goods',$goods);
        //商品类型
        //商品与型号的关系信息表
        $models=Db::name('goods_model')->where('gid',$id)->select();
        $mids[]='';
        foreach ($models as $val){
            $mids[]=$val['mid'];
        }
        $this->assign('mids',$mids);
        //型号的信息表
        $model=Db::name('models')->select();
        $this->assign('model',$model);

        return $this->fetch('goods/show');
    }
    //商品分类
    public function getOrder(){
        $Category=new \app\admin\model\Category();
        $data=$Category->tree();
        return $data;
    }
    //商品的栏目选择
    public function getTop_section(Request $request){
        $pid=\input('get.pid');
        $data=Db::name('category')->where('pid',$pid)->select();
        return $data;
    }
    //商品的品牌选择
    public function getChoose_brand(){
        $cid=\input('get.cid');
        $data=Db::name('brand')->where('cate_id',$cid)->select();
        return $data;
    }

}
?>